﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Mime
{
    using System;
    using System.IO;

    using Mews.IO;

    /// <summary>Processes the body of a binary entity.</summary>
    internal sealed class ImageBodyProcessor : UnstructuredContentProcessor, ILineProcessor<Body>
    {
        private readonly Func<MemoryStream, Body> makeResult;

        /// <summary>See <see cref="ILineProcessor{T}.GetResult"/>.</summary>
        public Body GetResult()
        {
            return this.makeResult(this.GetContent());
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal ImageBodyProcessor(
            EncodingTransformation encodingTransformation, string subtype, Disposition disposition) :
            base(encodingTransformation)
        {
            this.makeResult = content =>
                {
                    try
                    {
                        var result = new ImageBody(subtype);
                        result.Disposition = disposition;
                        result.SetContent(content);
                        return result;
                    }
                    catch (ArgumentException)
                    {
                        var result = new ApplicationBody(
                            new FallbackReason(FallbackReasonKind.UnrecognizedImageFormat, subtype));
                        result.Disposition = disposition;
                        result.SetContent(content);
                        return result;
                    }
                };
        }
    }
}
